/*
 * This file is part of Plop Messenger.
 *
 * Plop Messenger is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  Plop Messenger is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Plop Messenger.  If not, see <http://www.gnu.org/licenses/>.
 */
package pm.ui;

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import pm.Chan;
import pm.ChanListener;
import pm.util.ModifiableIterator;

public class ChanelPanel extends JPanel implements Chan,
		HistoryJTextFieldListener {

	private static final long serialVersionUID = 1L;
	private List<ChanListener> listeners = new ArrayList<ChanListener>();
	private JScrollPane scrollPane;
	private JTextArea textArea = new JTextArea();
	private HistoryJTextField textField = new HistoryJTextField(50);

	public ChanelPanel() {
		this.setLayout(new BorderLayout());
		scrollPane = new JScrollPane(textArea);
		textArea.setEditable(false);
		textField.addListener(this);
		this.add(scrollPane, BorderLayout.CENTER);
		this.add(textField, BorderLayout.SOUTH);
	}
	
	public void setVisible(boolean b){
		super.setVisible(b);
		textField.requestFocus();
	}

	public void addListener(ChanListener e) {
		listeners.add(e);
	}

	@Override
	public void newText(HistoryJTextField historyJTextField, String text) {
		if (historyJTextField == textField) {
			for (ChanListener l : new ModifiableIterator<ChanListener>(
					listeners)) {
				l.newCommand(this, text);
			}
		}
	}

	public void removeListener(ChanListener e) {
		listeners.remove(e);
	}

	@Override
	public void write(String str) {
		textArea.setText(textArea.getText() + str);
		textArea.setCaretPosition(textArea.getText().length());
	}

	@Override
	public void writeln(String str) {
		write(str + "\n");
	}

}
